package yjpay.api.web.control;

import java.util.ResourceBundle;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.util.encrypt.AES;
import com.util.encrypt.EncryUtil;
import com.util.encrypt.RSA;

/**
 * 回调代码示例
 * 
 * @author junqinghuang
 * 
 */
@Controller
public class PayCallbackWebCtrl {
	private ResourceBundle resb1 = ResourceBundle.getBundle("payapi");

	// 从配置文件读取易宝分配的公钥
	private String yibaoPublicKey = resb1
			.getString("payapi.paytest_yibao_publickey");

	// 从配置文件读取商户自己的私钥
	private String merchantPrivateKey = resb1
			.getString("payapi.paytest_merchant_privatekey");

	// 商户账户编号
	private String merchantaccount = resb1
			.getString("payapi.paytest_merchantaccount");

	@RequestMapping(value = "/pay/to_checkcallback")
	public ModelAndView checkCallback(Model model) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("pay/callback_check.jsp");
		return modelAndView;
	}

	@RequestMapping(value = "/pay/callback")
	public ModelAndView callback(Model model,
			@RequestParam("data") String yb_data,
			@RequestParam("encryptkey") String yb_encryptkey) throws Exception {

		System.out.println("商户回调地址接收到的参数值data为：" + yb_data);
		System.out.println("商户回调地址接收到的参数值encryptkey为：" + yb_encryptkey);

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("yb_data", yb_data);
		modelAndView.addObject("yb_encryptkey", yb_encryptkey);
		modelAndView.setViewName("pay/callback_result.jsp");

		try {

			// 对易宝返回的结果进行验签
			boolean passSign = EncryUtil.checkDecryptAndSign(yb_data,
					yb_encryptkey, yibaoPublicKey, merchantPrivateKey);

			if (passSign) {
				// 验签通过
				String yb_aeskey = RSA.decrypt(yb_encryptkey,
						merchantPrivateKey);

				System.out.println("易宝支付给商户" + merchantaccount
						+ "返回结果中使用的aeskey为：" + yb_aeskey);
				modelAndView.addObject("yb_aeskey", yb_aeskey);

				String payresult_view = AES.decryptFromBase64(yb_data,
						yb_aeskey);
				System.out.println("易宝支付给商户" + merchantaccount
						+ "结果（aes解密后的明文）：" + payresult_view);
				modelAndView.addObject("payresult_view", payresult_view);

			} else {
				System.out.println("验签未通过");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return modelAndView;
		}
		return modelAndView;
	}

}
